package com.qunar.wan.task;

import com.qunar.wan.common_api.model.EmailTask;
import com.qunar.wan.common_api.service.ActivityService;
import com.qunar.wan.common_api.service.EmailService;
import com.qunar.wan.common_api.service.UserActivityService;
import com.qunar.wan.email.EmailSender;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import java.util.Date;
import java.util.List;

/**
 * User: devry Date: 12/18/13 Time: 4:10 PM
 */
@Component("activityNoticeTask")
public class ActivityNoticeTask {
    private Logger logger = LoggerFactory.getLogger(getClass());
    @Resource
    private EmailService emailService;
    @Resource
    private ActivityService activityService;

    public void run() {
            List<EmailTask> emailTaskList = emailService.selectEmailTask();
            for (EmailTask emailTask : emailTaskList) {
                try {
                    long start = System.currentTimeMillis();
                    EmailSender.send(emailTask.getEmailType(), activityService.selectById(emailTask.getActId()),
                            emailTask.getUserEmail());
                    emailService.deleteEmailTask(emailTask.getId());
                    logger.info("ActivityNoticeTask 于{} send email,actid is {},the email type is {}, receiver is {},耗时{} ", new Date(),
                            emailTask.getActId(), emailTask.getEmailType().getSubject(), emailTask.getUserEmail(),
                            System.currentTimeMillis() - start);

                    } catch (Exception e) {
                        logger.info("ActivityNoticeTask 于{} send email,actid is {},the email type is {}, receiver is {},occured an exception {}", new Date(),
                        emailTask.getActId(), emailTask.getEmailType().getSubject(), emailTask.getUserEmail(), e);
                        continue;
                    }

            }
        }
}
